// SMUserFollowListViewController.m
#import "SMUserFollowListViewController.h"
#import "SMUserFollowCell.h"
#import <MJRefresh/MJRefresh.h>
#import "SMAPIClient.h"

@interface SMUserFollowListViewController ()
@property(nonatomic, copy) NSString *uid;
@property(nonatomic, assign) SMUserFollowMode mode;
@property(nonatomic, strong) NSMutableArray<NSDictionary*> *data;
@property(nonatomic, assign) NSInteger page;
@property(nonatomic, assign) BOOL hasMore;
@end

@implementation SMUserFollowListViewController

- (instancetype)initWithUserId:(NSString *)uid mode:(SMUserFollowMode)mode {
    if (self = [super initWithStyle:UITableViewStylePlain]) {
        _uid = [uid copy];
        _mode = mode;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.backgroundColor = UIColor.systemGroupedBackgroundColor;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableView registerClass:SMUserFollowCell.class forCellReuseIdentifier:@"cell"];

    self.data = [NSMutableArray array];
    self.page = 1; self.hasMore = YES;

    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refresh)];
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMore)];
    [self.tableView.mj_header beginRefreshing];
}

- (void)refresh {
    self.page = 1; self.hasMore = YES;
    [self request:self.page];
}

- (void)loadMore {
    if (self.hasMore) {
        self.page++;
        [self request:self.page]; // ✅ 正确调用
    } else {
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    }
}

#pragma mark - Networking with fallback
- (void)request:(NSInteger)page {
    NSString *kind = (self.mode==SMUserFollowModeFollowing ? @"following" : @"fans");
    NSString *path = [NSString stringWithFormat:@"user/%@/%@", self.uid ?: @"0", kind];
    NSDictionary *params = @{@"page":@(page), @"pageSize":@(10)};

    __weak typeof(self) weakSelf = self;
    [[SMAPIClient shared] GET:path parameters:params success:^(id json) {
        NSArray *arr = nil;
        if ([json isKindOfClass:NSDictionary.class] && [json[@"data"] isKindOfClass:NSArray.class]) {
            arr = json[@"data"];
        } else if ([json isKindOfClass:NSArray.class]) {
            arr = (NSArray *)json;
        }
        if (!arr) {
            [weakSelf apply:[weakSelf fallback:page] page:page];
            return;
        }
        NSMutableArray *ret = [NSMutableArray array];
        for (NSDictionary *d in arr) {
            if (![d isKindOfClass:NSDictionary.class]) continue;
            NSString *av   = d[@"avatar"] ?: @"";
            NSString *name = d[@"name"] ?: @"用户";
            NSString *intro= d[@"intro"] ?: @"诚心合作";
            BOOL following = [d[@"following"] boolValue];
            [ret addObject:@{@"avatar":av, @"name":name, @"intro":intro, @"following":@(following)}];
        }
        [weakSelf apply:ret page:page];
    } failure:^(NSError *error) {
        [weakSelf apply:[weakSelf fallback:page] page:page];
    }];
}

- (NSArray *)fallback:(NSInteger)page {
    NSMutableArray *arr = [NSMutableArray array];
    for (int i=0; i<10; i++) {
        NSString *a = [NSString stringWithFormat:@"https://i.pravatar.cc/100?u=%@_%ld_%d", self.uid,(long)page,i];
        NSString *n = [NSString stringWithFormat:@"%@ %@", (self.mode==SMUserFollowModeFollowing?@"关注":@"粉丝"), @(i+1)];
        NSString *intro = (arc4random_uniform(2)==0)?@"重废供应，稳定发货":@"回收工厂废料，诚信合作";
        BOOL f = (self.mode==SMUserFollowModeFollowing);
        [arr addObject:@{@"avatar":a, @"name":n, @"intro":intro, @"following":@(f)}]; // ✅ 正确 addObject
    }
    return arr;
}

- (void)apply:(NSArray *)arr page:(NSInteger)page {
    if (page == 1) [self.data removeAllObjects];
    [self.data addObjectsFromArray:arr];
    self.hasMore = arr.count >= 10;

    [self.tableView reloadData];
    [self.tableView.mj_header endRefreshing];
    if (self.hasMore) [self.tableView.mj_footer endRefreshing];
    else [self.tableView.mj_footer endRefreshingWithNoMoreData];
}

#pragma mark - Table
- (NSInteger)tableView:(UITableView*)t numberOfRowsInSection:(NSInteger)s { return self.data.count; }
- (CGFloat)tableView:(UITableView*)t heightForRowAtIndexPath:(NSIndexPath*)i { return 76; }
- (UITableViewCell*)tableView:(UITableView*)t cellForRowAtIndexPath:(NSIndexPath*)i {
    SMUserFollowCell *c = [t dequeueReusableCellWithIdentifier:@"cell" forIndexPath:i];
    NSDictionary *d = self.data[i.row];
    [c configureWithAvatar:d[@"avatar"] name:d[@"name"] intro:d[@"intro"] following:[d[@"following"] boolValue]];
    return c;
}
@end
